package com.ykg.util;

import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import java.security.Key;
import java.util.Date;

/**
 * TODO
 * 类(接口)：
 * Created on 8:27 2021/6/23.
 *
 * @Author: laobian
 * @Description:
 */
@Data
@Component
@ConfigurationProperties(prefix = "demo.jwt")
public class JwtUtil {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private String secret;
    private long expire;
    private String header;
    private Key key;

    /**
     * 生成jwt token
     *
     * @param userId
     * @return jws
     */
    public String generateToken(String userId) {
        Date nowDate = new Date();
        // 过期时间
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);
        key = Keys.hmacShaKeyFor(secret.getBytes());

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(userId)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(key)
                .compact();
    }

    /**
     * 根据token后去生成token中写入的内容
     *
     * @param token 用户token
     * @return {sub=1, iat=1581927676, exp=1582532476}
     */
    public Claims getClaimByToken(String token) {
        try {
            key = Keys.hmacShaKeyFor(secret.getBytes());
            return Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            logger.debug("validate is token error ", e);
            return null;
        }
    }

    /**
     * 判断token是否过期 expiration(2月24号) < new Date()(2月17号) 则过期
     *
     * @param expiration Claims中存储的过期时间
     * @return true 代表过期
     */
    public boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }
}

